using MongoDB.Driver;
using Sustainalytics.Synchronization.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Sustainalytics.ClientDW.Synchronization.SyncESGData.AbstractClassesAndInterfaces
{
    public abstract class SyncEsgCommand<T>
    {
        protected readonly ILogger Logger;

        protected SyncEsgCommand(ILogger logger)
        {
            this.Logger = logger;
        }

        public async Task ExecuteAsync(IList<T> entities, IList<Guid> companiesIds = null, Guid? additionalDiscriminator = null)
        {
            var stopWatch = Stopwatch.StartNew();

            var result = await DeleteAssociatedRecordsAsync(companiesIds, additionalDiscriminator);

            if (entities.Count > 0)
            {
                await InsertRecordsAsync(entities);
            }

            stopWatch.Stop();
            Logger.Log($" in collection {typeof(T).Name} " +
                        (companiesIds != null ? $"{result.DeletedCount} records were removed from {companiesIds.Count} companies and " : string.Empty) +
                        (additionalDiscriminator.HasValue ? $"using {additionalDiscriminator} as an additional discriminator and " : string.Empty) +
                        $"{entities.Count} records were added in {stopWatch.Elapsed}");
        }

        protected abstract Task<DeleteResult> DeleteAssociatedRecordsAsync(IEnumerable<Guid> companiesIds = null, Guid? additionalDiscriminator = null);

        protected abstract Task InsertRecordsAsync(IEnumerable<T> entities);
    }
}
